import { getModule, Module, Mutation, VuexModule } from 'vuex-module-decorators';
import store from '@/store';
import { KE } from '@/.ke/ke';
import { Route, RouteConfig } from 'vue-router';

@Module({ name: 'menu', dynamic: true, namespaced: true, store })
export default class MenuStore extends VuexModule {
    private _: string[] = [];
    private $top: KE.TopNav[] = [];

    get topNavs(): KE.TopNav[] {
        // console.log('top_mavs', this.$top)
        return this.$top ?? [];
    }

    get opens(): string[] {
        return this._;
    }

    /// 初始化当前打开菜单
    @Mutation
    initMenu({ route, topNavs, routes }: { route: Route, topNavs: KE.TopNav[], routes: RouteConfig[] }) {
        this.$top = topNavs;

        let breadcrumbs: any[] = [
            {
                title: '首页',
                route: 'Index'
            },
        ];
        let name: string = '';
        let get = (li: any[]) => {
            for (let k of li) {
                breadcrumbs = [];
                breadcrumbs.push({
                    title: k.meta?.title,
                    route: k.path,
                });
                if (k.name === route.name) {
                    this._.push(k.path);
                    break;
                } else {
                    if (k.opened) {
                        this._.push(k.path);
                    }
                    if (k.children && k.children.length) {
                        for (let s of k.children) {
                            if (s.name === route.name) {
                                breadcrumbs.push({
                                    title: k.meta?.title,
                                    route: s.path,
                                });
                                name = s.path;
                                this._.push(k.path);
                                break;
                            }
                        }
                    }
                }
            }
        }
        get(routes);

        console.log(['bread', breadcrumbs])

        // console.log('path', ops, name)
    }

    @Mutation
    setOpen(route: string) {
        const idx = this._.findIndex((_) => route === _);
        if (idx === -1) {
            this._.push(route);
        } else {
            this._.splice(idx, 1);
        }
    }
}

export const MenuModule = getModule(MenuStore);
